package com.wsx.ones.monitor.core.serialize.hession;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.wsx.ones.monitor.core.codec.Serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * hession序列化的实现
 *
 * Created by wangshuaixin on 17/2/4.
 */
public class Hession2Serialization implements Serialization {

    /**
     * hession的序列化操作，将对象转化成字节码
     * @param object
     * @return
     * @throws IOException
     */
    public byte[] serializ(Object object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Hessian2Output hession = new Hessian2Output(baos);
        hession.writeObject(object);
        hession.flush();
        return baos.toByteArray();
    }

    /**
     * hession的反序列化，将字节转换成对象，并且是指定类型的对象
     * @param bytes
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public <T> T deserializ(byte[] bytes, Class<T> clazz) throws IOException {
        Hessian2Input hession = new Hessian2Input(new ByteArrayInputStream(bytes));
        return (T) hession.readObject(clazz);
    }


    /**
     * hession的反序列化实现
     * @param bytes
     * @return
     * @throws IOException
     */
    public Object deserializ(byte[] bytes) throws IOException {
        Hessian2Input hession = new Hessian2Input(new ByteArrayInputStream(bytes));
        return hession.readObject();
    }
}
